#include<bits/stdc++.h>
using namespace std;
int a[200001],l[200001],pos[1000001],f[100001];
int main(){
    freopen("color.in","r",stdin);freopen("color.out","w",stdout);
    int t;cin >> t;
    while(t--){
        memset(a,0,sizeof(a));memset(l,0,sizeof(l));memset(pos,0,sizeof(pos));memset(f,1,sizeof(f));
        int n;cin >> n;int cnt = 0;
        for(int i = 1;i <= n;i++){
            scanf("%d",&a[i]);
            if(pos[a[i]]) l[i] = pos[a[i]];
            else l[i] = -1;
            pos[a[i]] = i;
        }
        for(int i = n;i >= 1;i--){
            if(l[i] != -1 && f[i]){
                int maxn = a[i];
                for(int j = i;j > l[i];j--){
                    if(l[j] != -1 && l[j] <= l[i]) maxn = max(maxn,a[j]),f[i] = 0;
                }
                cnt += maxn;
            }
        }
        cout << cnt << endl;
    }
    return 0;
}
